import axios, {
  AxiosError,
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
} from 'axios'
import { StoreKeys } from './enum'

const axiosClient: AxiosInstance = axios.create({
  timeout: 5000,
  // baseURL: 'https://test-wjx.xoyo.com/short-video-server',
  baseURL: '/short-video-server',
  headers: {
    'Content-Type': 'application/json',
    'Cache-control': 'public, max-age=31536000', // 缓存静态资源，public表示可在代理服务器共享缓存
  },
})

axiosClient.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    console.log('--config--', config)
    const token = localStorage.getItem(StoreKeys.token)
    console.log('--token--', token)
    if (token && config && config.headers) {
      config.headers.Authorization = token
    }
    return config
  },
  (error: AxiosError) => {
    console.log('--request error--', error)
    return Promise.reject()
  }
)

axiosClient.interceptors.response.use(
  (response: AxiosResponse) => {
    const statusCode = response.status
    console.log('--response--', response)
    if (statusCode === 200) {
      return response
    } else {
      return Promise.reject()
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

export default axiosClient
